The following conventions are used throughout this document.
argname a required argument.
[argname] an optional argument.
(out) argname an output argument, typically requires a reference for this argument.
All methods and functions return TRUE on success. FALSE on failure or unless otherwise noted. If an error occurs the Perl built in variable, '$!' is set. A reference to '$!' as a string will return a string explaining the error.
Functions
Create((out)$ProcessObj,$ApplicationName,$CommandLine,$InheritHandles,$CreateOptions,$CurrentDir)
The Create function acts as a constructor for the Process class. The executable module ($ApplicationName) is executed and passed $CommandLine. $CommandLine is the full command line for the new process.
To execute a perl script:
$CommandLine = 'perl myscript.pl';
The options for CreateOptions are:
Option Name Description CREATE_DEFAULT_ERROR_MODE Give the new process the default error mode. CREATE_NEW_CONSOLE The new process has a new console. This can't be used with DETACHED_PROCESS. CREATE_NEW_PROCESS_GROUP The new process is the root of a new process group. CREATE_SEPARATE_WOW_VDM The new process is run in it's own Virtual Dos Machine (VDM). Only applicable to 16-bit apps. CREATE_SUSPENDED The primary thread of the process is created in a suspended state. The process can be started with the Resume method below. CREATE_UNICODE_ENVIRONMENT The environment block of the new process uses UNICODE characters. DEBUG_PROCESS The calling process is treated as a debugger, and the new process is being debugged. DEBUG_ONLY_THIS_PROCESS If the calling process is being debugged, then the new process will not be debugged. DETACHED_PROCESS The new process does not have access to the console of the calling process.
Methods
Kill( $ExitCode)
Kills the process.
Suspend( )
Suspend the process.
Resume()
Resume a suspended process. This call can be used to resume a process that was created with the CREATE_SUSPENDED flag.
GetPriorityClass( (out) $Priority )
SetPriorityClass( $Priority )
The GetPriorityClass and SetPriorityClass methods allow control over the priority of the process. The $Priority can be one of
PriorityClass Description IDLE_PRIORITY_CLASS Indicates a process whose threads run only when the system is idle. (ex: screensaver ) fNORMAL_PRIORITY_CLASS Normal process scheduling. HIGH_PRIORITY_CLASS Indicates a process that performs time-critical tasks that must be executed immediately. REALTIME_PRIORITY_CLASS The highest process priority, even pre-empts OS threads.
GetExitCode( (out) $ExitCode );
GetExitCode can be used to find out how or if a process has exited.
Wait($Timeout)
Wait for the process to exit. Wait returns FALSE if it times out. $! Is set to WAIT_FAILED in this case.
Example
#'use' the process module. use Win32::Process; #theWin32:: module. Includes the Win32 error checking etc. # see Win32:: section for included functions. use Win32; sub Error{ print Win32::FormatMessage( Win32::GetLastError() ); } #Create the process object. Win32::Process::Create($ProcessObj, #object to hold process. "C:/winnt35/system32/Notepad.exe" #executable "Notepad temp.txt" #command line 0, #no inheritance. DETACHED_PROCESS, #separate process ".")|| die &Error; #current dir. #Set the process priority $ProcessObj->SetPriority(NORMAL_PRIORITY_CLASS)||die &Error; #Wait for the process to end. NO timeout $ProcessObj->Wait(INFINITE )|| die &Error; $ProcessObj->GetExitCode( $ExitCode )||die &Error; print" Notepad exited with $ExitCode\n";
Create ((out)$SemaphoreObj,$InitialCount,$MaxCount,$Name);
The Create Function creates a semaphore object and returns the reference in the $SemaphoreObj scalar. The semaphore is created with an initial value of $InitialCount. The maximum number of accesses allowed is set to $MaxCount. DESTROY( $SemaphoreObj )
The DESTROY Function destroys the Semaphore object. This method is automatically called by Perl when the $SemaphoreObject scalar goes out of scope.
Wait( $TimeOut )
The Wait method causes the calling process to wait on the Semaphore. If the Semaphore is not released in $TimeOut milliseconds, the call returns, and the return value should be checked. For no timeout value, use the predefined constant INFINITE. Release( $ReleaseCount ,(out) $lastCount)
The Release Method releases a semaphore and increments the count by $ReleaseCount. The value of the Semaphore before the change is recorded in the $LastCount var.
use Win32::Semaphore; use Win32; Win32::Semaphore::Create($Sem,1,1,"Sem")||die &Error; #wait for access to the shared resource. if( $Sem->Wait(INFINITE)){ #Access the shared resource here. &Access( $Shared_Resource ); $Sem->Release( 1,$last ); } else{ print"Could not get access to shared resource\n";}
WaitForMultipleObjects(@objects , $WaitAll ,$TimeOut );
The WaitForMultipleObjects is used to coordinate multiple events.The @objects array can hold objects of type: Semaphore, Mutex, Process, or ChangeNotification. If the $WaitAll var contains a true value ( non zero ) then the call waits for all of the objects, otherwise, it will return when the first object returns.
Win32::Semaphore::Create($Sem, 1,1,"Sem")||die $!; Win32::Mutex::Create( $mut,0,"Mut") ||die $!; #note: the WaitForMultipleObjects call is inherited, and # not referenced directly. Win32::Semaphore::WaitForMultipleObjects(($Sem,$mut),1, 10000 ) || die $!;
The IPC package is inherited by Win32::Process, Win32::Semaphore, Win32::ChangeNotification, and Win32::Mutex, it does not need to be implicitly 'use'd.
Create( (out) $MutexObj, $InitialOwner,$Name )
Create creates a mutex object and returns the reference in $MutexObj. If the $InitialOwner flag is set ( nonzero ) then the process calling the Create function has immediate ownership of the mutex. Otherwise, the mutex is available. $Name can be used by other processes in the Win32::Mutex::Open call to create an object to reference an already created mutex.
Open($MutexObj,$Name)
Open creates a mutex object to access an already Created mutex. The $Name must point to an already created object or this call will fail. Methods Release() Release relinquishes ownership of the mutex, allowing anyone Waiting on the mutex to take ownership.
Wait( $TimeOut );
Wait causes the calling process to wait for $TimeOut milliseconds for the ownership of the mutex. If the mutex doesn't come available before the timeout, the call returns false. To specifiy and infinite timeout, set $TimeOut to INFINITE.
#Create a mutex object Win32::Mutex::Create( $Mut,0, "MyMutex")|| die $!; #Use it . sub EnterArea { local( $mut ) = @_; $mut->wait( 5000 )||die $!; #access away!!! $mut->Release(); }
FindFirst( (out)$Object,$PathName,$WatchSubtree,$Filter)
Filter Option Description FILE_NOTIFY_CHANGE_FILE_NAME Any naming changes in the watched directory satisfy a change notification wait. Changes include renames, deletions, and creations. FILE_NOTIFY_CHANGE_DIR_NAME Any directory name changes. FILE_NOTIFY_CHANGE_ATTRIBUTES Any attritbute changes FILE_NOTIFY_CHANGE_SIZE Any file-size change. The notification only occurs when the change is written to disk. If disk IO is cached, the change occurs when the cache is flushed. FILE_NOTIFY_CHANGE_LAST_WRITE Any change to the last write time for a file. See above for notes on caching. FILE_NOTIFY_CHANGE_SECURITY Any security descriptor changes in the directory.
FindNext(); The FindNext method requests that the operating system signal the change notification object the next time it detects an appropriate change.
Close(); Stops the notification object monitoring.
Wait( $TimeOut) $TimeOut #time out in milliseconds. The Wait method causes the calling process to block until notification of the change.
DESTROY() The DESTROY method is called when the ChangeNotification object goes out of scope. This will close the notification.
Win32::ChangeNotification::FindFirst( $cnobj, "d:/mydir/",1," FILE_NOTIFY_CHANGE_FILE_NAME")||die $!; #Wait for the change. $cnobj->FindNext(); $cnobj->Wait( INFINITE ); #do something about the change. &Notify($Someone); $cnobj->Close;
Open( (out) $EventObj, $SourceName, [$ServerName]);
Open the eventlog on the specified machine, if no server is specified, the local machine is used. An Eventlog object is returned in $EventObj.
OpenBackup( (out)$EventObj, $FileName, [$ServerName]);
Open a backup eventlog and return an object to control it. If $ServerName is not given the local machine is used.
ReadFlag option Description EVENTLOG_FORWARDS_READ Eventlog is read in forward chronological order. EVENTLOG_BACKWARDS_READ Eventlog is read in reverse chronological order. EVENTLOG_SEEK_READ The read begins at the record specified by the $RecordOffset parameter. Must also specify EVENT_LOG_FORWARD_READ or EVENTLOG_BACKWARDS_READ. EVENTLOG_SEQUENTIAL_READ The read continues sequentially from the last read call.
See the Report method for information on the %EventInfo hash. Report( $Event, %EventInfo )
Reports an event. Implicitly calls RegisterEventSource.
The options for $Event are:
$Event Options Description EVENTLOG_ERROR_TYPE Error event EVENTLOG_WARNING_TYPE Warning event EVENTLOG_INFORMATION_TYPE Information event EVENTLOG_AUDIT_SUCCESS_TYPE Success Audit event EVENTLOG_AUDIT_FAILURE_TYPE Failure Audit event. %EventInfo contains the following: Key Value Category integer value for the category of the event (app defined ) EventID ID value of the Event. Source specific, any value. EventRawData The Raw binary data Strings Any text strings to merge user user name.
GetOldest( (out) $oldest ); Returns the Absolute record number of the oldest record in the event log.
GetNumber( (out) $NumberOfEvents ) Returns the number of events.
Clear( [ $filename ] ) If the $filename option is given, then the current eventlog is written to the file Clears the event log.
use Win32::Eventlog; sub TEST1{ my $number, $EventLog; OpenEventObj ( $EventLog , "System")|| die $!; $EventLog->GetNumberOfEvents( $number )|| die $!; print "There are $number records in the System Event Log\n"; }
sub TEST2{ # define the event to log. my $number, $EventLog; $Event = { 'EventType' => ERROR; 'Category' => 0; 'EventID' => 0x1003; 'EventRawData' => NULL; 'Strings' =>"SampleApp"; } # open the event log. OpenEventObj( $EventLog , "SamplApp")||die $!; #report the event and check the error $EventLog->ReportEvent( %$Event )||die $!;
When the Registry module is loaded, four Registry objects are created in the main:: namespace. These predefined registry objects are:
SetValue( $subkey,$type,$value);
QueryValue( (out)$value,(out)$type, $name )
QueryKey( (out)$class,(out)$NumberOfSubkeys,(out) NumberOfValues )
GetKeys( (out) \@Subkeys)
GetValues( (out)@Values )
Save( $filename)
Load( $subkey, $filename );
use Win32::Registry; $HKEY_LOCAL_MACHINE->Open($NewObj,"MyKey")||die $!; $NewObj->SetValue( "MySubKey",REG_SZ,5 );
UserCreate($server, $userName, $password,$passwordAge,$privilege,$homeDir, $comment, $flags, $scriptPath)
$Privilege options:
$flag options:
UserDelete($server, $user)
UserGetAttributes($server, $userName, $password, $passwordAge,$privilege,$homeDir, $comment, $flags, $scriptPath)
UserSetAttributes($server, $userName, $password, $passwordAge,$privilege, $homeDir, $comment, $flags, $scriptPath)
LocalGroupCreate($server, $group, $comment)
GroupCreate($server, $group, $comment)
LocalGroupDelete($server, $group)
GroupDelete($server, $group)
LocalGroupGetAttributes($server, $groupName, (out)$comment)
GroupGetAttributes($server, $groupName,(out)comment)
LocalGroupSetAttributes($server, $groupName, $comment)
GroupSetAttributes($server, $groupName, $comment)
LocalGroupAddUsers($server, $groupName, $users)
GroupAddUsers($server, $groupName, @users)
LocalGroupDelUsers($server, $groupName, @users)
GroupDelUsers($server, $groupName, @users)
LocalGroupIsMember($server, $groupName,$user)
GroupIsMember($server, $groupName, $user)
LocalGroupGetMembers($server, $groupName, (out)\@userArray)
GroupGetMembers($server, $groupName,(out) \@userArray)
use Win32::NetAdmin; # set info for the user. $userName = 'TestUser'; $password = ''; $passwordAge = 0; $privilege = USER_PRIV_USER; $homeDir = 'c:\\'; $comment = 'This is a test user'; $flags = UF_SCRIPT; $scriptpath = 'C:\\'; $groupName = 'TestGroup'; $groupComment = "This is a test group"; Win32::NetAdmin::UserCreate('', $userName, $password, $passwordAge, $privilege, $homeDir, $comment, $flags, $scriptpath ) || print "not "; Win32::NetAdmin::UserGetAttributes('',$userName, $Getpassword, $GetpasswordAge, $Getprivilege, $GethomeDir, $Getcomment, $Getflags, $Getscriptpath ) || warn(); ($password eq $Getpassword) || warn(); ($passwordAge == $GetpasswordAge) || warn(); ($homeDir eq $GethomeDir) || warn(); ($comment eq $Getcomment) || warn(); ($flags == ($Getflags&USER_PRIV_MASK)) || warn(); ($scriptpath eq $scriptpath) || warn();
GetAttributes( $filename,(out)$FileAttributes)
SetFileAttributes( $filename, $FileAttributes )
use Win32::File; Win32::File::GetAttributes( "myfile.txt",$Attributes)||die $!; Win32::File::SetAttributes( "myfile.txt",($Attributes | READONLY )) ||die $!;
StartService($hostname, $servicename )
StopService($hostname, $servicename )
GetStatus($hostname, $servicename, (out)$status )
PauseService($hostname ,$servicename ) ResumeService($hostname ,$servicename )
GetServices($hostname,(out)\@list )
#stop all services use Win32::Service; #Get a list of available services. Win32::Service::EnumServices(NULL,\@list ); #attempt to stop each service. foreach $Service (@list){ Win32::Service::StopService( NULL,$Service ); }
KEY VALUE 'netname' => Name of the share. 'type' => Type of share. 'remark' => A string comment. 'permissions' => Permissions value 'maxusers' => The max # of users. 'current-users' => The current # of users. 'path' => The path of the share. 'passwd' => A password if one is req'dNETRESOURCE
KEY VALUE 'Scope' => Scope of an Enumeration. See Scopes below. 'Type' => The type of resource to Enum. See Types below. 'DisplayType'=> The way the resource should be displayed.See Display below. 'Usage' => Specifies the Resources usage: see Usage below. 'LocalName' => Name of the local device the resource is connected to. 'RemoteName' => The network name of the resource. 'Comment' => A string comment. 'Provider' => Name of the provider of the resource. Scope values RESOURCE_CONNECTED The resource is already connected. RESOURCE_REMEMBERED The resource is reconnected each time the user logs on. RESOURCE_GLOBALNET The resource is available to the entire network. Type values: RESOURCETYPE_ANY All resources RESOURCETYPE_DISK Disk resources RESOURCETYPE_PRINT Print resources Display Type RESOURCEDISPLAYTYPE_DOMAIN The object should be displayed as a domain. RESOURCEDISPLAYTYPE_SERVER The object should be displayed as a server RESOURCEDISPLAYTYPE_SHARE The object should be displayed as a sharepoint. RESOURCEUSAGE_CONNECTABLE The resource can be connected to a local device. RESOURCEUSAGE_CONTAINER The resource contains more resources.
GetSharedResources((out)\@Resources,dwType)
AddConnection(\%NETRESOURCE,$Password,$UserName,$Connection)
CancelConnection($Name,$Connection,$Force)
WNetGetLastError((out)$ErrorCode(out),$Description,(out)$Name)
GetError( (out)$ErrorCode )
GetUNCName( (out)$UNCName, $LocalPath );
NetShareAdd(\%SHARE,$parm_err,$servername )
NetShareCheck($device,(out)$type,$servername)
NetShareDel( $netname, $servername )
NetShareGetInfo( $netname, (out)\%SHARE,$servername)
NetShareSetInfo( $netname,\%SHARE,(out)$parm_err,$servername)
use Win32::NetResource; use Win32; $ShareInfo = { 'path' => 'e:\\temp', 'netname' => "myshare", 'remark' => "This mine, leave it alone", 'passwd' => "", 'current-users' =>0, 'permissions' =>0, 'maxusers' => 10, 'type' => 10 }; Win32::NetResource::NetShareAdd( $ShareInfo,$parm )|| warn(); $NewShare = {}; Win32::NetResource::NetShareGetInfo("Temp",$NewShare) || warn(); $Aref=[]; Win32::NetResource::GetSharedResources($Aref,0); #try to connect to the Temp share. # Find the NETRESOURCE information for the Temp share. foreach $href (@$Aref ){ $myRef = $href if( $href->{'RemoteName'} =~ /Temp/ ); } $myRef->{'LocalName'}= "Z:"; Win32::NetResource::AddConnection($myRef,$passwd,$user,0); Win32::NetResource::GetUNCName($UNCName, "Z:" ); print "UNCName of the share is $UNCName\n"); Win32::NetResource::CancelConnection("Z:",0,1); Win32::NetResource::NetShareDel("Temp")|| print "not ";